package com.enjia.common.utils;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.Dialog;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Environment;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import com.enjia.enjiashop.MyApplication;

import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import okhttp3.FormBody;
import okhttp3.RequestBody;

public class CommonUtils {
    private static final String TAG = "CommonUtils";
    /**
     * 检测网络是否可用
     *
     * @param context
     * @return
     */
    public static boolean isNetworkAvailable(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
            if (mNetworkInfo != null&&mNetworkInfo.isConnected()) {
                if(mNetworkInfo.getState() == NetworkInfo.State.CONNECTED){
                    return true;
                }
            }
        }
        ToastUtil.showMessage(context,"无网络，请检查网络设置");
        return false;
    }
    public static boolean isNetworkAvailableNoTip(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
            if (mNetworkInfo != null) {
                return mNetworkInfo.isAvailable();
            }
        }
        return false;
    }

    public static boolean is3GConnected(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
            if (mNetworkInfo != null
                    && mNetworkInfo.isAvailable()
                    && mNetworkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
                return true;
            }
        }
        return false;
    }

    /**
     * 检测Sdcard是否存在
     *
     * @return
     */
    public static boolean isExitsSdcard() {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
            return true;
        else
            return false;
    }

    public  static String getString(Context context, int resId){
        return context.getResources().getString(resId);
    }

    public static void removeObject(Context context){
        File file = new File(context.getCacheDir()+"test.dat");
        if(file.exists()){
            file.delete();
        }
    }

    public static Object readObjectFromFile(Context context,String fileName) {
        Object temp = null;
        File file = new File(context.getCacheDir()+fileName);
        if(!file.exists()){
            return null;
        }
        FileInputStream in;
        try {
            in = new FileInputStream(file);
            ObjectInputStream objIn = new ObjectInputStream(in);
            temp=objIn.readObject();
            objIn.close();
            Log.e("保存用户信息：","read object success!");
        } catch (IOException e) {
            Log.e("保存用户信息：","read object failed");
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return temp;
    }

    public static void writeObjectToFile(Context context, String fileName,Object obj) {
        File file =new File(context.getCacheDir()+fileName);
        if(!file.exists()){
            try {
                file.createNewFile();
                FileOutputStream out;
                try {
                    out = new FileOutputStream(file);
                    ObjectOutputStream objOut=new ObjectOutputStream(out);
                    objOut.writeObject(obj);
                    objOut.flush();
                    objOut.close();
                    Log.e("保存用户信息：","write object success!");
                } catch (IOException e) {
                    Log.e("保存用户信息：","write object failed");
                    e.printStackTrace();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            file.delete();
            try {
                file.createNewFile();
                FileOutputStream out;
                try {
                    out = new FileOutputStream(file);
                    ObjectOutputStream objOut=new ObjectOutputStream(out);
                    objOut.writeObject(obj);
                    objOut.flush();
                    objOut.close();
                    Log.e("保存用户信息：","write object success!");
                } catch (IOException e) {
                    Log.e("保存用户信息：","write object failed");
                    e.printStackTrace();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static String timeExchange(String time){
        //排除掉小于0的情况
        Date date = new Date(Long.parseLong(time)<0?0: Long.parseLong(time));
        SimpleDateFormat formatter = new SimpleDateFormat("mm:ss");
        return formatter.format(date);
    }

    public static Bitmap convertViewToBitmap(View view){
//        view.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0,
//                View.MeasureSpec.UNSPECIFIED));
//        view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
        view.buildDrawingCache();
        Bitmap bitmap = view.getDrawingCache();
        return bitmap;
    }

    public static boolean isServiceWork(Context mContext, String serviceName) {
        boolean isWork = false;
        ActivityManager myAM = (ActivityManager) mContext
                .getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> myList = myAM.getRunningServices(40);
        if (myList.size() <= 0) {
            return false;
        }
        for (int i = 0; i < myList.size(); i++) {
            String mName = myList.get(i).service.getClassName().toString();
            if (mName.equals(serviceName)) {
                isWork = true;
                break;
            }
        }
        return isWork;
    }

    /**
     * 清理缓存
     *
     * @param context
     */
    public static void clearFrescoDiscCache(Context context) {
        /*ImagePipelineFactory imagePipelineFactory = ImagePipelineFactory.getInstance();
        if (imagePipelineFactory != null) {
            imagePipelineFactory.getMainBufferedDiskCache().clearAll();
            imagePipelineFactory.getSmallImageFileCache().clearAll();
//            imagePipelineFactory.getMainDiskStorageCache().clearAll();
            showToast(context, "缓存清理成功");
        }*/
    }

//    类型	Scheme	示例
//    远程图片	http://, https://	HttpURLConnection 或者参考 使用其他网络加载方案
//    本地文件	file://	FileInputStream
//    Content provider	content://	ContentResolver
//    asset目录下的资源	asset://	AssetManager
//    res目录下的资源	res://	Resources.openRawResource
//    res 示例:
//
//    Uri uri = Uri.parse("res://包名(实际可以是任何字符串甚至留空)/" + R.drawable.kaishuicon);

   /* public static void bindFrescoFromFile(Context context,
                                          SimpleDraweeView draweeView,
                                          String filePath ) {
        String uri = "file://"+ filePath;

        ImageRequest imageRequest =
                ImageRequestBuilder.newBuilderWithSource(Uri.parse(uri))
                        .setProgressiveRenderingEnabled(true)
                        .build();
        DraweeController draweeController = Fresco.newDraweeControllerBuilder()
                .setImageRequest(imageRequest)
                .setOldController(draweeView.getController())
                .setControllerListener(null)
                .setAutoPlayAnimations(true)
                .setTapToRetryEnabled(true)
                .build();
        draweeView.setController(draweeController);

    }*/

    /*public static void bindFrescoFromResource(Context context,
                                              SimpleDraweeView draweeView,
                                              int id ) {
        String uri = "res://"+ GlobalConstant.PACKAGENAME + id;

        ImageRequest imageRequest =
                ImageRequestBuilder.newBuilderWithSource(Uri.parse(uri))
                        .setProgressiveRenderingEnabled(true)
                        .build();
        DraweeController draweeController = Fresco.newDraweeControllerBuilder()
                .setImageRequest(imageRequest)
                .setOldController(draweeView.getController())
                .setControllerListener(null)
                .setAutoPlayAnimations(true)
                .setTapToRetryEnabled(true)
                .build();
        draweeView.setController(draweeController);
    }*/

    /*public static void bindFresco(Context context,
                                  SimpleDraweeView draweeView,
                                  String url ) {
        if(TextUtils.isEmpty(url)){
            return;
        }
        ImageRequest imageRequest =
                ImageRequestBuilder.newBuilderWithSource(Uri.parse(url))
                        .build();
        DraweeController draweeController = Fresco.newDraweeControllerBuilder()
                .setImageRequest(imageRequest)
                .setOldController(draweeView.getController())
                .setControllerListener(null)
                .setAutoPlayAnimations(true)
                .setTapToRetryEnabled(true)
                .build();
        draweeView.setController(draweeController);
    }*/

    public static String getDayTime(String blogtime) {
        long time = Long.parseLong(blogtime);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM-dd");
        return simpleDateFormat.format(new Date(time));
    }

    //
    public static String getCurrentTime() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM-dd");
        return simpleDateFormat.format(new Date());
    }

    public static String getDeaultBirthDay() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        return simpleDateFormat.format(new Date());
    }
    public static String getDuration(String durationstr){
        long time = Long.parseLong(durationstr);
        int s = (int) (time%60);
        int m = (int) ((time/60)%60);
        int h = (int) (time/60/60);
        if(h>0){
            return String.format("%02d:%02d:%02d",h,m,s);
        }else {
            return String.format("%02d:%02d",m,s);
        }
    }

    /**
     * 打开软键盘
     *
     * @param mEditText
     */
    public static void openKeybord(EditText mEditText) {
        InputMethodManager inputManager =
                (InputMethodManager) mEditText.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        inputManager.showSoftInput(mEditText, 0);
    }

    public static void hideSystemKeyBoard(Context mcontext, View v) {
        InputMethodManager imm = (InputMethodManager) ((Activity) mcontext)
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
    }


    /**
     * 关闭软键盘
     */
    //此方法只是关闭软键盘
//	public static void closeKeybord(Context context) {
//		if(context instanceof  Activity){
//			Activity activity = (Activity) context;
//			InputMethodManager imm = (InputMethodManager)activity.getSystemService(Context.INPUT_METHOD_SERVICE);
//			if(imm.isActive()&&activity.getCurrentFocus()!=null){
//				if (activity.getCurrentFocus().getWindowToken()!=null) {
//					imm.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
//				}
//			}
//		}
//	}

    /**
     * 隐藏软键盘
     *
     * @param context
     */
//	public static void hideSoftKeyboard(Context context) {
//		if (context instanceof FragmentActivity) {
//			FragmentActivity activity = (FragmentActivity) context;
//			if (activity != null) {
//				InputMethodManager imm = (InputMethodManager) context
//						.getSystemService(Context.INPUT_METHOD_SERVICE);
//				// imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
//				boolean isOpen=imm.isActive();//isOpen若返回true，则表示输入法打开  
//				if(isOpen){
//					imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
//				}else{
//				}
//			}
//		}
//	}

//    /**
//     * 查询下载的视频
//     */
//    public static File getDownVedio(String url) {
//        File dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/seed");
//        if (!dir.exists()) {
//            return null;
//        }
//        File downfile = new File(dir, CommonUtils.md5(url));
//        if (downfile.exists()) {
//            return downfile;
//        }
//        return null;
//    }

//    public static boolean isMobileNO(String mobiles) {
//            /*
//		    移动：134、135、136、137、138、139、150、151、157(TD)、158、159、187、188
//		    联通：130、131、132、152、155、156、185、186
//		    电信：133、153、180、189、（1349卫通）
//		    总结起来就是第一位必定为1，第二位必定为3或5或8，其他位置的可以为0-9
//		    17XXXXXXXXX 都有了
//		    */
////        String telRegex = "[1][358]\\d{9}";//"[1]"代表第1位为数字1，"[358]"代表第二位可以为3、5、8中的一个，"\\d{9}"代表后面是可以是0～9的数字，有9位。
//        String telRegex = "[1]\\d{10}";//"[1]"代表第1位为数字1，"[358]"代表第二位可以为3、5、8中的一个，"\\d{9}"代表后面是可以是0～9的数字，有9位。
//        if (TextUtils.isEmpty(mobiles)) return false;
//        else return mobiles.matches(telRegex);
//    }
//
//
//    public static GradientDrawable createRoundCornerShapeDrawable(
//            float radius, int fillColor) {
//        GradientDrawable drawable = new GradientDrawable();
//        drawable.setShape(GradientDrawable.RECTANGLE);
//        drawable.setStroke(0, Color.BLACK);
//        drawable.setCornerRadius(radius);
//        drawable.setColor(fillColor);
//        return drawable;
//    }
//
//
//    public static int getNavigationBarHeight(Activity activity) {
//        Resources resources = activity.getResources();
//        int resourceId = resources.getIdentifier("navigation_bar_height", "dimen", "android");
//        //获取NavigationBar的高度
//        int height = resources.getDimensionPixelSize(resourceId);
//        return height;
//    }
//
//
//    /**
//     * @param activity
//     * @return > 0 success; <= 0 fail
//     */
//    public static int getStatusHeight(Activity activity) {
//        int statusHeight = 0;
//        Rect localRect = new Rect();
//        activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(localRect);
//        statusHeight = localRect.top;
//        if (0 == statusHeight) {
//            Class<?> localClass;
//            try {
//                localClass = Class.forName("com.android.internal.R$dimen");
//                Object localObject = localClass.newInstance();
//                int i5 = Integer.parseInt(localClass.getField("status_bar_height").get(localObject).toString());
//                statusHeight = activity.getResources().getDimensionPixelSize(i5);
//            } catch (ClassNotFoundException e) {
//                e.printStackTrace();
//            } catch (IllegalAccessException e) {
//                e.printStackTrace();
//            } catch (InstantiationException e) {
//                e.printStackTrace();
//            } catch (NumberFormatException e) {
//                e.printStackTrace();
//            } catch (IllegalArgumentException e) {
//                e.printStackTrace();
//            } catch (SecurityException e) {
//                e.printStackTrace();
//            } catch (NoSuchFieldException e) {
//                e.printStackTrace();
//            }
//        }
//        return statusHeight;
//    }
//
//    /**
//     * 设置阴暗
//     */
//    public static void setDark(Activity activity) {
//        WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
//        lp.alpha = 0.7f;
//        activity.getWindow().setAttributes(lp);
//    }

    /**
     * 增加亮度
     */
    public static void setLight(Activity activity) {
        WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
        lp.alpha = 1.0f;
        activity.getWindow().setAttributes(lp);
    }


    /**
     * @param string
     * @return
     */
    public static String md5(String string) {
        byte[] hash;
        try {
            hash = MessageDigest.getInstance("MD5").digest(
                    string.getBytes("UTF-8"));
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("Huh, MD5 should be supported?", e);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("Huh, UTF-8 should be supported?", e);
        }

        StringBuilder hex = new StringBuilder(hash.length * 2);
        for (byte b : hash) {
            if ((b & 0xFF) < 0x10)
                hex.append("0");
            hex.append(Integer.toHexString(b & 0xFF));
        }
        return hex.toString();
    }

    /**
     * 验证邮箱
     *
     * @param email
     * @return
     */
    public static boolean checkEmail(String email) {
        boolean flag = false;
        try {
            String check = "^([a-z0-9A-Z]+[-|_|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
            Pattern regex = Pattern.compile(check);
            Matcher matcher = regex.matcher(email);
            flag = matcher.matches();
        } catch (Exception e) {
            flag = false;
        }
        return flag;
    }

    /**
     * 验证密码
     *
     * @param pwd
     * @return
     */
    public static boolean checkPwd(String pwd) {
        boolean flag = false;
        try {
            String check = "^[0-9a-zA-Z]{6,16}$";
            Pattern regex = Pattern.compile(check);
            Matcher matcher = regex.matcher(pwd);
            flag = matcher.matches();
        } catch (Exception e) {
            flag = false;
        }
        return flag;
    }

    /**
     * 验证手机号码
     *
     * @param mobileNumber
     * @return
     */
    public static boolean checkMobileNumber(String mobileNumber) {
        boolean flag = false;
        try {
            Pattern regex = Pattern
                    .compile("^(((13[0-9])|(15([0-3]|[5-9]))|(18[0,5-9]))\\d{8})|(0\\d{2}-\\d{8})|(0\\d{3}-\\d{7})$");
            Matcher matcher = regex.matcher(mobileNumber);
            flag = matcher.matches();
        } catch (Exception e) {
            flag = false;
        }
        return flag;
    }

    /**
     * 从assert中读取文件
     *
     * @param context
     * @param fileName
     * @return
     */
    public static String readContentFromAsset(Context context, String fileName) {
        String str = "";
        try {
            InputStream inputStream = context.getAssets().open(fileName);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            if (inputStream != null) {
                byte[] bs = new byte[1024];
                int ch = -1;
                while ((ch = inputStream.read(bs)) != -1) {
                    baos.write(bs, 0, ch);
                }
                str = baos.toString();
                baos.close();
                inputStream.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return str;
    }

    /**
     * 截取部分的字符串
     *
     * @param respond
     * @param jsonKey
     * @return
     */
    @SuppressWarnings("unused")
    public static String getPartJson(String respond, String jsonKey) {
        if (TextUtils.isEmpty(respond)) {
            return null;
        }
        try {
            JSONObject jsonObject = new JSONObject(respond);
            if (jsonObject != null) {
                return jsonObject.getString(jsonKey);
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 格式化文件大小
     *
     * @param fileSize
     * @return
     */
    public static String formetFileSize(long fileSize) {
        DecimalFormat df = new DecimalFormat("#.00");
        String fileSizeString = "";
        if (fileSize < 1024) {
            fileSizeString = df.format((double) fileSize) + "B";
        } else if (fileSize < 1048576) {
            fileSizeString = df.format((double) fileSize / 1024) + "K";
        } else if (fileSize < 1073741824) {
            fileSizeString = df.format((double) fileSize / 1048576) + "M";
        } else {
            fileSizeString = df.format((double) fileSize / 1073741824) + "G";
        }
        return fileSizeString;
    }

    /**
     * 判断是否有sd卡
     *
     * @return
     */
    public static boolean hasSdcard() {
        String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED)) {
            return true;
        } else {
            return false;
        }
    }

    // =================================================================================
    public static class SubDirectoriesAndSize {
        final public long size;
        final public List<File> subDirectories;

        public SubDirectoriesAndSize(final long totalSize,
                                     final List<File> theSubDirs) {
            size = totalSize;
            subDirectories = Collections.unmodifiableList(theSubDirs);
        }
    }

    public static SubDirectoriesAndSize getTotalAndSubDirs(final File file) {
        long total = 0;
        final List<File> subDirectories = new ArrayList<File>();
        if (file.isDirectory()) {
            final File[] children = file.listFiles();
            if (children != null)
                for (final File child : children) {
                    if (child.isFile())
                        total += child.length();
                    else
                        subDirectories.add(child);
                }
        }
        return new SubDirectoriesAndSize(total, subDirectories);
    }

    public static long getTotalSizeOfFilesInDir(final File file)
            throws InterruptedException, ExecutionException, TimeoutException {
        final ExecutorService service = Executors.newFixedThreadPool(100);
        try {
            long total = 0;
            final List<File> directories = new ArrayList<File>();
            directories.add(file);
            while (!directories.isEmpty()) {
                final List<Future<SubDirectoriesAndSize>> partialResults = new ArrayList<Future<SubDirectoriesAndSize>>();
                for (final File directory : directories) {
                    partialResults.add(service
                            .submit(new Callable<SubDirectoriesAndSize>() {
                                public SubDirectoriesAndSize call() {
                                    return getTotalAndSubDirs(directory);
                                }
                            }));
                }
                directories.clear();
                for (final Future<SubDirectoriesAndSize> partialResultFuture : partialResults) {
                    final SubDirectoriesAndSize subDirectoriesAndSize = partialResultFuture
                            .get(100, TimeUnit.SECONDS);
                    directories.addAll(subDirectoriesAndSize.subDirectories);
                    total += subDirectoriesAndSize.size;
                }
            }
            return total;
        } finally {
            service.shutdown();
        }
    }

    // =================================================================================

//    /**
//     * 获得异常信息 Constants.EXCEPTION_FILE_NAME Constants.LOG_FILE_PATH
//     *
//     * @return
//     */
//    public static String getExceptionInfo() {
//        File externalStorageDirectory = Environment
//                .getExternalStorageDirectory();
//        String path = externalStorageDirectory.getAbsolutePath()
//                + KaishuVariables.LOG_FILE_PATH;
//        File directory = new File(path);
//        if (!directory.exists()) {
//            directory.mkdirs();
//        }
//        StringBuilder sb = new StringBuilder();
//        File file = new File(new File(path),
//                KaishuVariables.EXCEPTION_FILE_NAME);
//        BufferedReader br = null;
//        if (file.exists()) {
//            try {
//                FileReader fr = new FileReader(file);
//                br = new BufferedReader(fr);
//                if (br != null) {
//                    while (br.ready()) {
//                        String myreadline = br.readLine();
//                        sb.append(myreadline);
//                    }
//                }
//            } catch (Exception e) {
//                e.printStackTrace();
//            } finally {
//                try {
//                    br.close();
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            }
//        }
//        return sb.toString();
//    }

    /**
     * 判断wifi是否连接
     *
     * @param context
     * @return
     */
    public static boolean isWifiConnected(Context context) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
        if (activeNetInfo != null
                && activeNetInfo.getType() == ConnectivityManager.TYPE_WIFI
                && activeNetInfo.isConnected()) {
            return true;
        }
        return false;
    }

    /**
     * 判断蜂窝有没有连接
     *
     * @param context
     * @return
     */
    public static boolean isMobileConnected(Context context) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
        if (activeNetInfo != null
                && activeNetInfo.getType() == ConnectivityManager.TYPE_MOBILE
                && activeNetInfo.isConnected()) {
            return true;
        }
        return false;
    }

//    /**
//     * 安装apk 用于版本更新
//     *
//     * @param context
//     */
//    public static void installApk(Context context) {
//        File file = new File(
//                Environment
//                        .getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
//                KaishuVariables.APK_NAME);
//        if (file.exists()) {
//            Intent intent = new Intent(Intent.ACTION_VIEW);
//            intent.setDataAndType(Uri.fromFile(file),
//                    "application/vnd.android.package-archive");
//            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//            context.startActivity(intent);
//        } else {
//            showToast(context, "沒有发现相应的apk");
//        }
//    }
//
//    public static void genNewApk(Context context, byte[] responseBody) {
//        //进行下载apk逻辑
//        File apkFile = new File(
//                Environment
//                        .getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
//                KaishuVariables.APK_NAME);
//        BufferedOutputStream bufferOs = null;
//        try {
//            bufferOs = new BufferedOutputStream(new FileOutputStream(apkFile));
//            bufferOs.write(responseBody);
//            bufferOs.flush();
//        } catch (Exception e) {
//            e.printStackTrace();
//        } finally {
//            if (bufferOs != null) {
//                try {
//                    bufferOs.close();
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            }
//        }
//
//    }
    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dp2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }
    /**
     * 根据手机的分辨率从 px 的单位 转成为 dp(像素)
     */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    /**
     * 显示踩 赞的动画
     *
     * @param context
     * @param content
     * @param anchor
     * @param imageview
     */
    // public static void startZanAnim(final Context context, String content,
    // TextView anchor, View imageview) {
    // PopShow popShow = new PopShow(context, content);
    // popShow.show(anchor, 500);
    //
    // Animation loadAnimation = AnimationUtils.loadAnimation(context,
    // R.anim.zan_anim);
    // imageview.startAnimation(loadAnimation);
    // }

    /**
     * avoid button fast click
     */
    private static long lastClickTime;

//    public static boolean isFastClick() {
//        long time = System.currentTimeMillis();
//        long timeD = time - lastClickTime;
//        // 避免快速点击*************
////        public static final int AVOID_FASTCLICK_TIME = 200;
//
//        if (0 < timeD && timeD < GlobalConstant.AVOID_FASTCLICK_TIME) {
//            return true;
//        }
//        lastClickTime = time;
//        return false;
//    }

    /**
     * show quit toast
     *
     * @param context
     * @param str
     */
    public static void showQuitAppToast(Context context, String str) {
        /**View layout = View.inflate(context, R.layout.view_quite_tip, null);
         layout.getBackground().setAlpha(200);
         TextView message = (TextView) layout.findViewById(R.id.message);
         message.setText(str);
         Toast toast = new Toast(context);
         toast.setGravity(Gravity.CENTER, 0, 0);
         toast.setDuration(Toast.LENGTH_SHORT);
         toast.setView(layout);
         toast.show();**/
    }




    /**
     * 获得屏幕的宽度
     *
     * @param context
     * @return
     */
    public static int getScreenW(Context context) {
        DisplayMetrics dm = new DisplayMetrics();
        WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        windowManager.getDefaultDisplay().getMetrics(dm);
        int screenWidth = dm.widthPixels;
        return screenWidth;
    }

    /**
     * 获得屏幕的高度
     *
     * @param context
     * @return
     */
    public static int getScreenH(Context context) {
        DisplayMetrics dm = new DisplayMetrics();
        WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        windowManager.getDefaultDisplay().getMetrics(dm);
        int screenWidth = dm.heightPixels;
        return screenWidth;
    }

    //设置Dialog所占屏幕的宽高比
    public static void setDialogSize(Context context,Dialog dialog,Double weightWei  ){
        Window dialogWindow = dialog.getWindow();
        WindowManager.LayoutParams p = dialogWindow.getAttributes(); // 获取对话框当前的参数值
        p.height = WindowManager.LayoutParams.WRAP_CONTENT; // 高度设置为屏幕的0.6，根据实际情况调整
        p.width = (int) (getScreenW(context) * weightWei); // 宽度设置为屏幕的0.65，根据实际情况调整
        dialogWindow.setAttributes(p);
    }

    /**
     * 刷新的时间格式
     *
     * @return
     */
//    public static String formatPullToRefreshDate(Context context) {
//        SimpleDateFormat sdf = new SimpleDateFormat(
//                KaishuVariables.REFRESH_DATA_FORMAT);
//        return getString(context, R.string.seed_today) + "  "
//                + sdf.format(new Date());
//    }

    public static int getGapCount(Date startDate, Date endDate) {
        Calendar fromCalendar = Calendar.getInstance();
        fromCalendar.setTime(startDate);
        fromCalendar.set(Calendar.HOUR_OF_DAY, 0);
        fromCalendar.set(Calendar.MINUTE, 0);
        fromCalendar.set(Calendar.SECOND, 0);
        fromCalendar.set(Calendar.MILLISECOND, 0);

        Calendar toCalendar = Calendar.getInstance();
        toCalendar.setTime(endDate);
        toCalendar.set(Calendar.HOUR_OF_DAY, 0);
        toCalendar.set(Calendar.MINUTE, 0);
        toCalendar.set(Calendar.SECOND, 0);
        toCalendar.set(Calendar.MILLISECOND, 0);
        return (int) ((toCalendar.getTime().getTime() - fromCalendar.getTime().getTime()) / (1000 * 60 * 60 * 24));
    }


    public static long getSecondInterval(long startTime){
        long currTime = System.currentTimeMillis();
        return (currTime - startTime)/1000;
    }

    /**
     * 隐藏软键盘
     */
    public static void hideKeyboard(Activity activity) {
        if (activity.getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
            if (activity.getCurrentFocus() != null)
                ((InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE))
                        .hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(),
                                InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }


    // facebook 用户获得key hash
    // public void ddd(){
    // try {
    // PackageInfo info = getPackageManager().getPackageInfo(
    // "com.oasgames.humorstation", //your unique package name here
    // PackageManager.GET_SIGNATURES);
    // for (Signature signature : info.signatures) {
    // MessageDigest md = MessageDigest.getInstance("SHA");
    // md.update(signature.toByteArray());
    // Log.d("KeyHash", Base64.encodeToString(md.digest(), Base64.DEFAULT));//
    // this line gives your keyhash
    // }
    // } catch (NameNotFoundException e) {
    //
    // } catch (NoSuchAlgorithmException e) {
    //
    // }
    // }

    /**
     *  获取应用的版本号。
     */
    public static String getAppVersion(Context context) {
            try {
                     PackageManager manager = context.getPackageManager();
                     PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
                     String version = info.versionName;
                     return version;
                 } catch (Exception e) {
                     e.printStackTrace();
                     return "";
                }
         }

    /**
     *  获取应用的版本号。
     */
    public static int getAppVersionCode(Context context) {
        try {
            PackageManager manager = context.getPackageManager();
            PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
            int versionCode = info.versionCode;
            return versionCode;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }
    /**
     * 版本对比(是否需要更新版本)
     *
     * @param newVersion
     *            服务器上获取的版本
     * @param indexVersion
     *            当前使用的版本
     * @return true：服务器上是最新版本，需要更新； false：不需要更新
     */
    public static boolean isUpdateForVersion(String newVersion, String indexVersion) {
        // boolean resultFlag = false;

        if ("".equals(newVersion) || null == newVersion
                || "null".equals(newVersion)) {
            return false;
        } else {
            String[] newNums = newVersion.split("\\.");
            String[] indexNums = indexVersion.split("\\.");
            if (newNums.length > indexNums.length) {// 服务器版本长度 比当前版本要长
                for (int i = 0; i < newNums.length; i++) {
                    //位数不够,给当前版本补零
                    int currentValue = 0;
                    if(i < indexNums.length){
                        currentValue = Integer.parseInt(indexNums[i]);
                    }
                    // 服务器上同位版本数如果有一个数大于 当前的，就是最新版，要更新；否则不更新
                    if (Integer.parseInt(newNums[i]) > currentValue) {
                        return true;
                    } else if (Integer.parseInt(newNums[i]) <= currentValue) {
//                        return false;
                    }
                }
                return false;
            } else if (newNums.length <= indexNums.length) {
                for (int i = 0; i < indexNums.length; i++) {
                    //位数不够,给服务器版本补零
                    int newValue = 0;
                    if(i < newNums.length){
                        newValue = Integer.parseInt(newNums[i]);
                    }
                    // 服务器上同位版本数如果有一个数大于 当前的，就是最新版，要更新；否则不更新
                    if (newValue > Integer.parseInt(indexNums[i])) {
                        return true;
                    } else if (newValue <= Integer.parseInt(indexNums[i])) {
//                        return false;
                    }
                }
                return false;
            }

        }
        return false;

    }
    /**
     *  为formBody添加公共的部分。
     */
    public static RequestBody addComment(Map<String,String> map,FormBody.Builder builder){
        String access_token = null;
        String str = "";

        if (MyApplication.userBean != null){
            access_token = MyApplication.userBean.getToken();
        }
        if(null != map){
            Set<String> keySet = map.keySet();
            Iterator<String> iter = keySet.iterator();

            while (iter.hasNext()) {
                String key = iter.next();
                str +=  map.get(key);
                builder.add(key,map.get(key));
            }
        }
       str = "MhxZkhl:Xhkj-Anxin@201705" + str;

        String result = md5(str);
        builder.add("ts",System.currentTimeMillis()+"");
        builder.add("sign",result);
        builder.add("version", CommonUtils.getAppVersion(MyApplication.context));
        builder.add("os","android");
        if (!TextUtils.isEmpty(access_token)) {
            builder.add("token",access_token);
        }

        return builder.build();
    }

    /**
     *  为GET请求添加公共参数
     */
    public static Map<String,String> addGETParam(Map<String,String> map,Context context){
        String str = "";
        String access_token = null;
        if (MyApplication.userBean != null){
            access_token = MyApplication.userBean.getToken();
        }

        //Collections.sort(list);
        Set<String> keySet = map.keySet();
        Iterator<String> iter = keySet.iterator();

        while (iter.hasNext()) {
            String key = iter.next();
            str +=  map.get(key);
        }
        str = "MhxZkhl:Xhkj-Anxin@201705" + str;
        String result = md5(str);
        map.put("ts",System.currentTimeMillis()+"");
        map.put("sign",result);
        map.put("version", CommonUtils.getAppVersion(context));
        map.put("os","android");
        if (!TextUtils.isEmpty(access_token)) {
            map.put("token", access_token);
        }

        ApplicationInfo appInfo = null;
        try {
            appInfo = MyApplication.context.getPackageManager().getApplicationInfo(MyApplication.context.getPackageName(), PackageManager.GET_META_DATA);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        String channel = "";
        if (appInfo != null && appInfo.metaData != null && appInfo.metaData.getString("UMENG_CHANNEL") != null ) {
            channel = appInfo.metaData.getString("UMENG_CHANNEL");
        }
        map.put("channel", channel);
        return map;
    }
    /**
     * 金额格式化
     * @param s 金额
     * @param len 小数位数
     * @return 格式后的金额
     */
    public static String insertComma(String s, int len) {
        if (s == null || s.length() < 1) {
            return "";
        }
        NumberFormat formater = null;
        double num = Double.parseDouble(s);
        if (len == 0) {
            formater = new DecimalFormat("###");
        } else {
            StringBuffer buff = new StringBuffer();
            buff.append("##0.");
            for (int i = 0; i < len; i++) {
                buff.append("0");
            }
            formater = new DecimalFormat(buff.toString());
        }
        return formater.format(num);
    }

    // 两次点击按钮之间的点击间隔不能少于1000毫秒
    private static final int MIN_CLICK_DELAY_TIME = 1000;
    private static long lastClickTime1;

    public static boolean isFastClick() {
        boolean flag = false;
        long curClickTime = System.currentTimeMillis();
        if ((curClickTime - lastClickTime1) >= MIN_CLICK_DELAY_TIME) {
            flag = true;
        }
        lastClickTime1 = curClickTime;
        return flag;
    }
}